package com.apotik.legenda.dao;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.apotik.legenda.model.Insurance;
import com.apotik.legenda.util.HibernateUtil;

public class InsuranceDao extends CommonDao<Insurance> {

	private SessionFactory sessionFactory;
	
	public InsuranceDao() {
		super(Insurance.class);
		
		sessionFactory = HibernateUtil.getSessionFactory();
		setSessionFactory(sessionFactory);
	}
	
	@SuppressWarnings("unchecked")
	public List<Insurance> listByAnyCriteria(boolean isActive, String searchValue, int first, int max){
		List<Insurance> list = new ArrayList<>();
		
		try {
			Session session = sessionFactory.openSession();
			
			Criteria cr = session.createCriteria(Insurance.class);
			cr.add(Restrictions.eq("isActive", isActive));
			
			if(!searchValue.trim().equalsIgnoreCase("")){
				Criterion criterion = Restrictions.ilike("insuranceName", "%"+searchValue+"%");
				cr.add(criterion);
			}
			
			cr.setFirstResult(first);
			cr.setMaxResults(max);
			cr.addOrder(Order.asc("insuranceId"));
			list = cr.list();
			
			session.close();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
		}
		
		return list;
	}
	
	@SuppressWarnings({ "rawtypes" })
	public int size(boolean activeCount, boolean activeValue, String searchValue){
		int result = 0;
		
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Criteria cr = session.createCriteria(Insurance.class);
			
			if(activeCount){
				cr.add(Restrictions.eq("isActive", activeValue));
			}
			
			if(!searchValue.trim().equalsIgnoreCase("")){
				Criterion criterion = Restrictions.ilike("insuranceName", "%"+searchValue+"%");
				cr.add(criterion);
			}
			
			cr.setProjection(Projections.rowCount());
			
			List list = cr.list();
			
			if(list!=null){
				result = (int) list.get(0);
			}
			
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
		}
		
		return result;
	}

}
